<template>
  <div class="container">
    <div class="sidebar">
      <a-table
        :columns="columnsTree"
        :data="data.treeData"
        :pagination="false"
        @row-click="rowClickFunc"
        class="my-table"
      >
        <template #tr="{ record }">
          <tr :class="data.actRow === record.satelliteId ? 'my-tr' : ''"></tr>
        </template>
      </a-table>
    </div>
    <div class="main-content">
      <div class="settings">
        <a-button
          type="primary"
          @click="openModal"
          style="width: 100px; float: right; z-index: 99; margin-bottom: 20px; cursor: pointer"
        >
          新建
        </a-button>
        <a-spin :loading="data.loading">
          <a-table :data="data.satData" :pagination="false">
            <template #columns>
              <a-table-column title="序号" data-index="satName">
                <template #cell="{ rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column title="关联分析名称" data-index="name"></a-table-column>
              <a-table-column title="遥测参数" data-index="paramName">
                <template #cell="{ record }">
                  {{ record.paramsList.map((item) => item.paramName).join('、') }}
                </template>
              </a-table-column>
              <!-- <a-table-column title="正常结果范围">
                <template #cell="{ record }">
                  {{ Number(record.upperLimit).toFixed(2) }} ~
                  {{ Number(record.lowerLimit).toFixed(2) }}
                </template>
              </a-table-column> -->
              <a-table-column title="备注" data-index="notes"></a-table-column>
              <a-table-column title="操作" :width="255" align="center">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" @click="editConfigItem(record, true)"
                      ><template #icon><IconZoomIn /></template>详情</a-button
                    >
                    <a-button type="text" status="success" style="color: #00b3b3" @click="editConfigItem(record, false)"
                      ><template #icon><IconEdit /></template>修改</a-button
                    >
                    <a-button type="text" status="warning" @click="deleteConfigItem(record)"
                      ><template #icon><IconDelete /></template>删除</a-button
                    >
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
          <a-pagination
            class="my-1"
            style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
            :total="data.paginationData.total"
            :current="data.paginationData.page"
            :page-size="data.paginationData.pageSize"
            show-total
            show-jumper
            show-page-size
            @change="handleCurrentChange"
            @page-size-change="handleSizeChange"
          />
        </a-spin>
      </div>
    </div>
  </div>
  <!-- 弹窗 -->
  <a-modal
    v-if="showModal"
    v-model:visible="showModal"
    :title="modalTitle"
    @before-ok="handleSubmit"
    @cancel="handleCancel"
    class="modelCont"
    :width="860"
    :footer="!isInfo"
  >
    <a-form :model="form" ref="formRef" :disabled="isInfo" class="formData">
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="关联分析名称"
            field="name"
            label-col-flex="120px"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <a-input v-model="form.name" v-if="!isInfo" placeholder="请输入"> </a-input>
            <div v-else>{{ form.name }}</div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="遥测参数"
            field="paramsList"
            label-col-flex="120px"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <a-select v-if="!isInfo" v-model="form.paramsList" value-key="paramId" placeholder="请选择" multiple>
              <a-option
                v-for="(item, index) in data.ycParamList"
                :key="index"
                :value="item"
                :label="item.paramName + '(' + item.paramCode + ')'"
              ></a-option>
            </a-select>
            <div v-else>
              {{ form.paramsList.map((item) => item.paramName + '(' + item.paramCode + ')')?.join(',') }}
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            label="自定义脚本"
            field="visitor"
            label-col-flex="120px"
            :rules="[{ required: true, message: '请输入' }]"
          >
            <Editor ref="editorRef" :readonly="isInfo" :value="form.visitor" @update:value="handleUpdateValue" />
          </a-form-item>
        </a-col>
      </a-row>
      <!-- <a-row v-if="!isInfo">
        <a-col :span="13">
          <a-form-item
            label="正常结果范围"
            field="upperLimit"
            label-col-flex="120px"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <a-input-number
              v-model="form.upperLimit"
              :precision="2"
              placeholder="请输入"
            >
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="1" style="text-align: center; line-height: 30px">-</a-col>
        <a-col :span="10">
          <a-form-item
            hide-label
            field="lowerLimit"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <a-input-number
              v-model="form.lowerLimit"
              :precision="2"
              placeholder="请输入"
            >
            </a-input-number>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-else>
        <a-col>
          <a-form-item
            label="正常结果范围"
            field="upperLimit"
            label-col-flex="120px"
            :rules="[{ required: true, message: '请选择' }]"
          >
            <div>{{ form.upperLimit.toFixed(2) }} - {{ form.lowerLimit.toFixed(2) }}</div>
          </a-form-item>
        </a-col>
      </a-row> -->
      <a-row>
        <a-col :span="24">
          <a-form-item label="备注" field="notes" label-col-flex="120px">
            <a-textarea v-if="!isInfo" v-model="form.notes" placeholder="请输入" style="height: 130px"> </a-textarea>
            <div v-else>{{ form.notes }}</div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { apiHome } from '@/api'
import { apiAnalysis } from '@/api/analysis'
import Editor from './edit.vue'

const columnsTree = [
  {
    title: '卫星',
    dataIndex: 'satelliteName'
  }
]
const data = reactive({
  loading: false,
  treeData: [],
  actRow: '',
  satData: [],
  ycParamList: [],
  paginationData: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  }
})

const FORM = {
  name: '',
  paramsList: [],
  visitor: 'function() { \r\n \r\n }',
  upperLimit: 0,
  lowerLimit: 2,
  notes: ''
}

const modalTitle = ref('新建参数关联分析')
const showModal = ref(false)
const formRef = ref(null)
const editorRef = ref(null)
const form = ref({ ...FORM })
const isInfo = ref(false)

const openModal = () => {
  modalTitle.value = '新建参数关联分析'
  isInfo.value = false
  form.value = { ...FORM }
  showModal.value = true
  // editorRef.value.initMonaco();
}

const handleUpdateValue = (newValue) => {
  form.value.visitor = newValue
}

const editConfigItem = (row, type) => {
  isInfo.value = type
  modalTitle.value = type ? '查看参数关联分析' : '编辑参数关联分析'
  apiAnalysis.getRelationParamsDetail(row.id).then((res) => {
    if (res.code === 200) {
      showModal.value = true
      form.value = res.data
      form.value.upperLimit = +res.data.upperLimit
      form.value.lowerLimit = +res.data.lowerLimit
      console.log(form.value)
    }
  })
}

const deleteConfigItem = (row) => {
  Modal.confirm({
    title: '提示',
    content: '确定删除该参数关联分析吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      apiAnalysis.deleteRelationParams(row.id).then((res) => {
        if (res.code === 200) {
          Message.success('删除成功')
          getTableData()
        }
      })
    }
  })
}

const handleSubmit = (done) => {
  formRef.value.validate((errors) => {
    if (!errors) {
      console.log('success', form.value)
      done(false)
      if (form.value.upperLimit > form.value.lowerLimit) return Message.error('上限值不能大于下限值')

      form.value = {
        ...form.value,
        satId: form.value.paramsList[0].satId,
        satCode: form.value.paramsList[0].satCode,
        satName: form.value.paramsList[0].satName
      }
      const api = form.value.id ? apiAnalysis.updateRelationParams : apiAnalysis.addRelationParams
      api(form.value).then((res) => {
        if (+res.code === 200) {
          getTableData()
          handleCancel()
          Message.success(form.value.id ? '编辑成功' : '新建成功')
          done()
        } else {
          done(false)
        }
      })
    } else {
      console.log('error', errors)
      done(false)
    }
  })
  // console.log('55555555')
  // const apiMethod = form.value.id
  //   ? apiHome.putOperatorMgr
  //   : apiHome.operatorMgr;
  // apiMethod(form.value).then(() => {
  //   Message.success(form.value.id ? "修改成功" : "提交成功");
  //   showModal.value = false;
  //   fetchPageList();
  // });
}

const handleCancel = () => {
  showModal.value = false
  formRef.value.resetFields()
}

const handleCurrentChange = (page) => {
  data.paginationData.pageNum = page
  getTableData()
}

const handleSizeChange = (size) => {
  data.paginationData.pageSize = size
  getTableData()
}

const getTreeData = () => {
  apiHome.satellites().then((res) => {
    if (+res.code === 200) {
      data.treeData = res.data || []
      data.actRow = res.data[0].satelliteId
      getTableData()
      getSelectParams()
    }
  })
}

const getTableData = () => {
  data.loading = true
  apiAnalysis
    .getRelationParams({
      pageNum: 1,
      pageSize: 10,
      satelliteId: data.actRow || 0
    })
    .then((res) => {
      if (+res.code === 200) {
        data.loading = false
        data.paginationData.total = +res.data?.total || 0
        data.satData = res.data?.list || []
      }
    })
    .finally(() => {
      data.loading = false
    })
}

const getSelectParams = () => {
  apiHome.getSelectParams({ satId: data.actRow }).then((res) => {
    data.ycParamList = res?.data || []
  })
}

const rowClickFunc = (record) => {
  data.actRow = record.satelliteId
  getTableData()
  getSelectParams()
}

onMounted(() => {
  getTreeData()
})
</script>

<style lang="less" scoped>
.container {
  display: flex;
  min-height: calc(100vh - 56px);
}

.sidebar {
  width: 250px;
  padding: 20px;
  border-right: 1px solid #f0f0f0;
}
h2 {
  text-align: center;
  font-family:
    Microsoft YaHei,
    Microsoft YaHei,
    serif;
  font-weight: bold;
  font-size: 18px;
  color: #222222;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.settings {
  margin-bottom: 20px;
}
.lookBtn {
  color: #1d68d0;
}
.modelCont {
  width: 860px;
}
.btnBox {
  display: flex;
  div {
    margin-right: 10px;
    cursor: pointer;
  }
}
.my-tr {
  background: #1d68d0;
  color: #fff;
  :deep(td) {
    background: #1d68d0;
    color: #fff;
  }
}
.my-tr :hover {
  background: #1d68d0;
  color: #fff;
}
.my-table tr {
  cursor: pointer;
}
</style>
